'use strict';

/**
 * @ngdoc service
 * @name jgappApp.FileService
 * @description
 * # FileService
 * Service in the jgappApp.
 */
angular.module('jgappApp')
    .service('FileService', ["openApi", "DataService", '$q', 'Util', '$location', function(openApi, DataService, $q, Util, $location) {
        // AngularJS will instantiate a singleton by calling "new" on this function
        var FileService = {}
        FileService.upload = function(imgData,url) {
            var delay = $q.defer();
            // Util.showLoadingStatus()
            Util.loadingStatus(0);
            var win = function(r) {
                // Util.hideLoadingStatus();
                Util.loadingStatus(100);
                var data = JSON.parse(r.response).result
                delay.resolve(data);
            }
            var fail = function(error) {
                alert("上传附件出错");
                // Util.hideLoadingStatus();
                Util.loadingStatus(100);
                delay.reject(error);
            }
            var options = {};
            var params = {};
            params.fileName=Date.now()+".jpg";
            options.params = params;
            var ft = new FileTransfer();
            ft.onprogress = function(progressEvent) {
                if (progressEvent.lengthComputable) {
                    var num = parseInt((progressEvent.loaded / progressEvent.total).toFixed(2) * 100,10);
                    Util.loadingStatus(num);
                    // Util.showLoadingStatus()
                }
            };
            // Util.showLoadingStatus()
            ft.upload(imgData, url, win, fail, options);
            return delay.promise;
        }
        FileService.delfile = function(imgData) {
            var delay = $q.defer();
            var param = {};
            param.fileName = imgData
            DataService.getData(openApi.deleteFile, param).then(function(data) {
                delay.resolve(data);
            });
            return delay.promise;
        }
        FileService.showfile = function(imgData) {
            if (!imgData || !imgData.match((/.((jpg)|(png)|(gif)|(jpeg))+/g))) {
                Util.Toast("移动端不支持预览")
                return
            } else {
                $location.path("showfile/" + imgData)
            }
        }
        return FileService
    }]);
